<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Controller {

	public function index()
	{
		//$this->load->view('welcome_message');
	}

	public function login(){
		//$post = $GLOBALS['HTTP_RAW_POST_DATA'];
		$post = file_get_contents("php://input");
		$request =  json_decode($post,true);
		if (NULL != $request ){
			$res = $this->db->get_where('users', array('name' => $request['name']))->result();
			if($res == NULL){
				echo json_encode(array('status' => 'failed','info'=>'username_not_found'));
				exit;
			}else{
				$res = $res[0];
			}
			//var_dump($res);
			if(md5($request['password']) == $res->password){
				//echo "OK";
				if((time()-strtotime($res->update)) > 3600){
					$update_data = array('update'=>date('Y-m-d H:i:s'),'token'=>uniqid());
					$this->db->update('users', $update_data, array('id' => $res->id));
					echo json_encode(array('status'=>'success','token' => $update_data['token']));
				}else{
					echo json_encode(array('status'=>'success','token' => $res->token));
				}
			}else{
				echo json_encode(array('status' => 'failed','info'=>'password_incorrect'));
			}
		}else{
			echo json_encode(array('status' => 'failed','info'=>'format_error'));
		}
	}


}